/**
 * Copyright 2014 wasu.com
 *
 *
 * Create on 2014-12-19 下午3:23:35
 */
package xj.toolkit.netty.handler.codec.http.reactor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import xj.toolkit.base.Sender;
import xj.toolkit.netty.handler.codec.http.request.HttpRequestExt;
import xj.toolkit.netty.handler.codec.http.response.ConstantResponse;
import xj.toolkit.netty.handler.codec.http.transformer.HttpTransformException;
import xj.toolkit.netty.transport.TransportUtils;
import xj.toolkit.netty.util.NettyConstants;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;

/**
 * @author <a href="mailto:caoxiaojian@wasu.com>xiaojian.cao</a>
 * 
 */
public class HttpErrorHnadlerReactor implements HttpErrorReactor {

	private static final Logger logger = LoggerFactory.getLogger(HttpErrorHnadlerReactor.class);

	private HttpReactor nextReactor = null;

	/**
	 * @return the nextReactor
	 */
	public HttpReactor getNextReactor() {
		return nextReactor;
	}

	/**
	 * @param nextReactor
	 *            the nextReactor to set
	 */
	public void setNextReactor(HttpReactor nextReactor) {
		this.nextReactor = nextReactor;
	}

	/**
	 * @see xj.toolkit.netty.handler.codec.http.reactor.HttpErrorReactor#onError(io.netty.handler.codec.http.FullHttpRequest,
	 *      java.lang.Exception)
	 */
	@Override
	public void onError(FullHttpRequest request, Exception exception) {
		Assert.isInstanceOf(HttpRequestExt.class, request, "request must be type of HttpRequestExt");
		HttpRequestExt requestExt = (HttpRequestExt) request;

		HttpResponse resp = ConstantResponse.get400NobodyResponse();
		if (exception instanceof HttpTransformException) {
			HttpTransformException httpTransformException = (HttpTransformException) exception;
			resp = ConstantResponse.getWithCodeDesc(httpTransformException.getCauseCode(),
					httpTransformException.getCauseDesc(), NettyConstants.TXT_TYPE,
					httpTransformException.getCauseDesc());
		} else {
			resp = ConstantResponse.getWithCodeDesc(HttpResponseStatus.BAD_REQUEST, NettyConstants.TXT_TYPE,
					exception.getMessage());
		}

		String uuid = request.headers().get(NettyConstants.HEADER_UUID);
		if (uuid != null) {
			resp.headers().set(NettyConstants.HEADER_UUID, uuid);
		}

		Sender sender = TransportUtils.getSenderOf(requestExt);
		if (sender == null) {
			logger.error("Cannot get sender of FullHttpRequest[{}].", request);
		} else {
			sender.send(resp);
		}

		if (null != this.nextReactor) {
			nextReactor.onHttpRequest(request);
		}

	}

}
